package com.woniuxy.dudugua.shiro;

import com.woniuxy.dudugua.entity.User;
import com.woniuxy.dudugua.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * 定义用户认证授权类，领域
 */
public class UserRealm extends AuthorizingRealm {
    //注入业务层
    @Resource
    private UserService userService;

    /**
     * 这个是授权认证的方法
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 这个是身份认证的方法
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        User user = userService.loginByTel((String) token.getPrincipal());
        System.out.println("认证的用户信息"+user);
        try{
            if(user!=null){
                SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
                return info;
            }
        }catch (Exception e){
            throw new AuthenticationException("服务器异常");
        }
        return null;
    }
}
